<!-- build time:Tue Dec 17 2019 19:26:45 GMT+0800 (GMT+08:00) --><!doctype html><html class="theme-next mist" lang="zh-Hans"><head><meta name="generator" content="Hexo 3.8.0"><meta name="google-site-verification" content="7Tau9WyVgxnsEY9oYedu9g0U6_8akOX3wiKbaYcrg9A"><meta name="baidu-site-verification" content="EVwLiaxdxX"><link href="/css/xps13.css" rel="stylesheet" type="text/css"><link href="/css/message.css" rel="stylesheet" type="text/css"><script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css"><meta name="keywords" content="Nginx,"><link rel="alternate" href="/atom.xml" title="MrBird" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1"><meta name="description" content="Nginx配置文件主要分成四部分：main（全局设置）、http（HTTP的通用设置）、server（虚拟主机设置）、location（匹配URL路径）。还有一些其他的配置段，如event，upstream等。一个完整的Nginx配置如下："><meta name="keywords" content="Nginx"><meta property="og:type" content="article"><meta property="og:title" content="Nginx的基本配置"><meta property="og:url" content="http://mrbird.cc/Nginx basic config.html"><meta property="og:site_name" content="MrBird"><meta property="og:description" content="Nginx配置文件主要分成四部分：main（全局设置）、http（HTTP的通用设置）、server（虚拟主机设置）、location（匹配URL路径）。还有一些其他的配置段，如event，upstream等。一个完整的Nginx配置如下："><meta property="og:locale" content="zh-Hans"><meta property="og:image" content="http://mrbird.cc/img/mrbird_pohto_20171101114239.png"><meta property="og:image" content="http://mrbird.cc/img/mrbird_photo_20171101112838.png"><meta property="og:image" content="http://mrbird.cc/img/mrbird_photo_20171101151244.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20171101151332.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20171101151521.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20171101151607.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20171101151711.png"><meta property="og:updated_time" content="2019-10-28T12:14:46.255Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Nginx的基本配置"><meta name="twitter:description" content="Nginx配置文件主要分成四部分：main（全局设置）、http（HTTP的通用设置）、server（虚拟主机设置）、location（匹配URL路径）。还有一些其他的配置段，如event，upstream等。一个完整的Nginx配置如下："><meta name="twitter:image" content="http://mrbird.cc/img/mrbird_pohto_20171101114239.png"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Mist",sidebar:{position:"left",display:"always",offset:12,offset_float:0,b2t:!1,scrollpercent:!1},fancybox:!1,motion:!1}</script><title>Nginx的基本配置 | MrBird</title></head><body ondragstart="return!1" class="animsition" lang="zh-Hans" style="overflow-x:hidden;padding-right:280px"><script type="text/javascript" src="/js/mo.min.js"></script><style>@media (min-width:768px) and (max-width:991px){body .header-innerr{width:700px!important}}.header-innerr{margin:0 auto;padding:100px 0 70px;width:880px}@media (min-width:1600px){.container .header-innerr{width:1200px}}.header-innerr{position:relative}.header-innerr{padding:20px 0 0}.header-innerr:after,.header-innerr:before{content:" ";display:table}.header-innerr:after{clear:both}@media (max-width:767px){.header-innerr{width:auto;padding:10px;margin-bottom:-20px}}</style><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><link href="https://fonts.font.im/css?family=Merienda" rel="stylesheet"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title" style="font-family:Merienda;font-size:1.3rem">MrBird</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle"></p></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section">HOME</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">ARCHIVES</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section">TAGS</a></li><li class="menu-item menu-item-friends"><a href="/friends/" rel="section">FRIENDS</a></li><div class="sidebar-toggle" style="display:none"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="Search" spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div><div class="header-innerr"><div class="note info" style="margin:0;letter-spacing:.15px">🐤手把手教你搭建<strong>Spring Cloud微服务权限系统</strong>（从零到部署）：<a style="color:#40dab2;font-weight:600" href="https://www.kancloud.cn/mrbird/spring-cloud" target="_blank">https://www.kancloud.cn/mrbird/spring-cloud</a></div></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://mrbird.cc/Nginx basic config.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="MrBird"><meta itemprop="description" content=""><meta itemprop="image" content="/images/blogImage.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="MrBird"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">Nginx的基本配置</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">Posted on</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-18T10:18:08+08:00">2017-10-18 </time></span><span></span> <span class="post-meta-divider">|</span> <span class="page-pv"><i class="fa fa-laptop"></i>&nbsp;&nbsp;Visit count <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body" itemprop="articleBody"><p>Nginx配置文件主要分成四部分：main（全局设置）、http（HTTP的通用设置）、server（虚拟主机设置）、location（匹配URL路径）。还有一些其他的配置段，如event，upstream等。</p><p>一个完整的Nginx配置如下：</p><a id="more"></a><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">user</span>       www www;  <span class="comment">## Default: nobody</span></span><br><span class="line"><span class="attribute">worker_processes</span>  <span class="number">5</span>;  <span class="comment">## Default: 1</span></span><br><span class="line"><span class="attribute">error_log</span>  logs/error.log;</span><br><span class="line"><span class="attribute">pid</span>        logs/nginx.pid;</span><br><span class="line"><span class="attribute">worker_rlimit_nofile</span> <span class="number">8192</span>;</span><br><span class="line"></span><br><span class="line"><span class="section">events</span> &#123;</span><br><span class="line">  <span class="attribute">worker_connections</span>  <span class="number">4096</span>;  <span class="comment">## Default: 1024</span></span><br><span class="line">  <span class="attribute">multi_accept</span> <span class="literal">on</span>;</span><br><span class="line">  <span class="attribute">use</span> <span class="literal">epoll</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="section">http</span> &#123;</span><br><span class="line">  <span class="attribute">include</span>    conf/mime.types;</span><br><span class="line">  <span class="attribute">include</span>    /etc/nginx/proxy.conf;</span><br><span class="line">  <span class="attribute">include</span>    /etc/nginx/fastcgi.conf;</span><br><span class="line">  <span class="attribute">index</span>    index.html index.htm index.php;</span><br><span class="line"></span><br><span class="line">  <span class="attribute">default_type</span> application/octet-stream;</span><br><span class="line"></span><br><span class="line">  <span class="attribute">log_format</span>   main <span class="string">'<span class="variable">$remote_addr</span> - <span class="variable">$remote_user</span> [<span class="variable">$time_local</span>]  <span class="variable">$status</span> '</span></span><br><span class="line">                    <span class="string">'"<span class="variable">$request</span>" <span class="variable">$body_bytes_sent</span> "<span class="variable">$http_referer</span>" '</span></span><br><span class="line">                    <span class="string">'"<span class="variable">$http_user_agent</span>" "<span class="variable">$http_x_forwarded_for</span>"'</span>;</span><br><span class="line"></span><br><span class="line">  <span class="attribute">access_log</span>   logs/access.log  main;</span><br><span class="line">  <span class="attribute">sendfile</span>     <span class="literal">on</span>;</span><br><span class="line">  <span class="attribute">tcp_nopush</span>   <span class="literal">on</span>;</span><br><span class="line">  <span class="attribute">server_names_hash_bucket_size</span> <span class="number">128</span>; <span class="comment"># this seems to be required for some vhosts</span></span><br><span class="line"></span><br><span class="line">  <span class="section">server</span> &#123; <span class="comment"># php/fastcgi</span></span><br><span class="line">    <span class="attribute">listen</span>       <span class="number">80</span>;</span><br><span class="line">    <span class="attribute">server_name</span>  domain1.com www.domain1.com;</span><br><span class="line">    <span class="attribute">access_log</span>   logs/domain1.access.log  main;</span><br><span class="line">    <span class="attribute">root</span>         html;</span><br><span class="line"></span><br><span class="line">    <span class="attribute">location</span> <span class="regexp">~ \.php$</span> &#123;</span><br><span class="line">      <span class="attribute">fastcgi_pass</span>   <span class="number">127.0.0.1:1025</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="section">server</span> &#123; <span class="comment"># simple reverse-proxy</span></span><br><span class="line">    <span class="attribute">listen</span>       <span class="number">80</span>;</span><br><span class="line">    <span class="attribute">server_name</span>  domain2.com www.domain2.com;</span><br><span class="line">    <span class="attribute">access_log</span>   logs/domain2.access.log  main;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># serve static files</span></span><br><span class="line">    <span class="attribute">location</span> <span class="regexp">~ ^/(images|javascript|js|css|flash|media|static)/</span>  &#123;</span><br><span class="line">      <span class="attribute">root</span>    /var/www/virtual/big.server.com/htdocs;</span><br><span class="line">      <span class="attribute">expires</span> <span class="number">30d</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment"># pass requests for dynamic content to rails/turbogears/zope, et al</span></span><br><span class="line">    <span class="attribute">location</span> / &#123;</span><br><span class="line">      <span class="attribute">proxy_pass</span>      http://127.0.0.1:8080;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="attribute">upstream</span> big_server_com &#123;</span><br><span class="line">    <span class="attribute">server</span> <span class="number">127.0.0.3:8000</span> weight=<span class="number">5</span>;</span><br><span class="line">    <span class="attribute">server</span> <span class="number">127.0.0.3:8001</span> weight=<span class="number">5</span>;</span><br><span class="line">    <span class="attribute">server</span> <span class="number">192.168.0.1:8000</span>;</span><br><span class="line">    <span class="attribute">server</span> <span class="number">192.168.0.1:8001</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="section">server</span> &#123; <span class="comment"># simple load balancing</span></span><br><span class="line">    <span class="attribute">listen</span>          <span class="number">80</span>;</span><br><span class="line">    <span class="attribute">server_name</span>     big.server.com;</span><br><span class="line">    <span class="attribute">access_log</span>      logs/big.server.access.log main;</span><br><span class="line"></span><br><span class="line">    <span class="attribute">location</span> / &#123;</span><br><span class="line">      <span class="attribute">proxy_pass</span>      http://big_server_com;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="Nginx基础配置指令"><a href="#Nginx基础配置指令" class="headerlink" title="Nginx基础配置指令"></a>Nginx基础配置指令</h2><h3 id="user"><a href="#user" class="headerlink" title="user"></a>user</h3><p>用于指定运行Nginx的用户和组：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">user</span> user [group]</span><br></pre></td></tr></table></figure><p></p><p>只有被设置的用户或者用户组成员才有权限启动Nginx服务。如果希望所有用户都可以启动Nginx，则只需将其注释掉或者指定为：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">user</span> nobody nobody</span><br></pre></td></tr></table></figure><p></p><h3 id="worker-processes"><a href="#worker-processes" class="headerlink" title="worker_processes"></a>worker_processes</h3><p>指定Nginx的工作进程的个数，可以设置为与 CPU 数量相同，基本语法：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">worker_processes</span> number|auto</span><br></pre></td></tr></table></figure><p></p><p>设置为auto时，Nginx进程将自动检测。当worker_processes设置为1时：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># sbin/nginx </span></span><br><span class="line"><span class="comment"># ps -ef|grep nginx</span></span><br><span class="line"><span class="attribute">root</span>      <span class="number">5882</span>  <span class="number">1326</span>  <span class="number">0</span> <span class="number">13</span>:<span class="number">07</span> ?        <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span> nginx: master process sbin/nginx</span><br><span class="line">nobody    <span class="number">5883</span>  <span class="number">5882</span>  <span class="number">0</span> <span class="number">13</span>:<span class="number">07</span> ?        <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span> nginx: worker process</span><br><span class="line">root      <span class="number">5885</span>  <span class="number">5430</span>  <span class="number">0</span> <span class="number">13</span>:<span class="number">07</span> pts/<span class="number">1</span>    <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span> grep --color=auto nginx</span><br></pre></td></tr></table></figure><p></p><p>将worker_processes设置为3时：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># ps -ef|grep nginx</span></span><br><span class="line"><span class="attribute">root</span>      <span class="number">5919</span>  <span class="number">1326</span>  <span class="number">0</span> <span class="number">13</span>:<span class="number">09</span> ?        <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span> nginx: master process sbin/nginx</span><br><span class="line">nobody    <span class="number">5920</span>  <span class="number">5919</span>  <span class="number">0</span> <span class="number">13</span>:<span class="number">09</span> ?        <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span> nginx: worker process</span><br><span class="line">nobody    <span class="number">5921</span>  <span class="number">5919</span>  <span class="number">0</span> <span class="number">13</span>:<span class="number">09</span> ?        <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span> nginx: worker process</span><br><span class="line">nobody    <span class="number">5922</span>  <span class="number">5919</span>  <span class="number">0</span> <span class="number">13</span>:<span class="number">09</span> ?        <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span> nginx: worker process</span><br><span class="line">root      <span class="number">5924</span>  <span class="number">5430</span>  <span class="number">0</span> <span class="number">13</span>:<span class="number">09</span> pts/<span class="number">1</span>    <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span> grep --color=auto nginx</span><br></pre></td></tr></table></figure><p></p><p>worker_processes进程数变成了3个。</p><h3 id="error-log"><a href="#error-log" class="headerlink" title="error_log"></a>error_log</h3><p>用于配置错误日志的存放路径。http，server和location块也可配置error_log，区别在于级别不一样。基本语法：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">error_log</span> files|stderr [ <span class="literal">debug</span> | <span class="literal">info</span> | <span class="literal">notice</span> | <span class="literal">warn</span> | <span class="literal">error</span> | <span class="literal">crit</span> | alert | emerg ]</span><br></pre></td></tr></table></figure><p></p><p>debug级别最高，emerg级别最低。比如设置级别为warn后，warn，error，crit，alert和emerg级别的日志都会被记录。Nginx默认日志存放路径为：<code>logs/error.log</code>。</p><h3 id="pid"><a href="#pid" class="headerlink" title="pid"></a>pid</h3><p>pid指令用于指定存放Nginx主进程号存放文件的路径。默认的路径为：</p><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># ./sbin/nginx </span></span><br><span class="line"><span class="comment"># cat logs/nginx.pid </span></span><br><span class="line">101106</span><br></pre></td></tr></table></figure><p></p><h3 id="worker-rlimit-nofile"><a href="#worker-rlimit-nofile" class="headerlink" title="worker_rlimit_nofile"></a>worker_rlimit_nofile</h3><p>设置毎个进程的最大文件打开数。如果不设的话上限就是系统的ulimit –n的数字（1024）。</p><h3 id="worker-connections"><a href="#worker-connections" class="headerlink" title="worker_connections"></a>worker_connections</h3><p>设定一个worker进程的最大连接数。默认为512，按自己系统的硬件配置调整，不能超过worker_rlimit_nofile。</p><h3 id="include"><a href="#include" class="headerlink" title="include"></a>include</h3><p>include指令用于引入第三方配置文件，比如常见的MIME类型等。</p><h3 id="accept-mutex"><a href="#accept-mutex" class="headerlink" title="accept_mutex"></a>accept_mutex</h3><p>该条指令目的是为了解决“惊群”的问题。“惊群”大致意思是：当某个时刻只有一个网络连接时，多个进程会被同时唤醒，但最终实际上只有一个进程可以获得连接，由于唤醒了别的不必要的进程，造成了性能的浪费。</p><p>accept_mutex语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">accept_mutex</span> <span class="literal">on</span> | <span class="literal">off</span></span><br></pre></td></tr></table></figure><p></p><p>默认为开启（on）状态，只能在events块中进行设置。</p><h3 id="multi-accept"><a href="#multi-accept" class="headerlink" title="multi_accept"></a>multi_accept</h3><p>用于设置是否允许worker_process同时接受多个网络连接。语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">multi_accept</span> <span class="literal">on</span> | <span class="literal">off</span></span><br></pre></td></tr></table></figure><p></p><p>其默认为关闭（off）状态，也就是说每个worker_process一次只能接收一个新到达的网络连接。</p><p>该指令只能在events模块中设置。</p><h3 id="use"><a href="#use" class="headerlink" title="use"></a>use</h3><p>use指令用于选择事件的驱动模型。语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">use</span> method</span><br></pre></td></tr></table></figure><p></p><p>Nginx提供了多种事件驱动模型来处理网络消息，method可选的内容有：select，poll，kqueue，epoll，rtsig，/dev/poll和eventport。</p><p>该指令只能在events模块中设置。</p><h3 id="worker-connentions"><a href="#worker-connentions" class="headerlink" title="worker_connentions"></a>worker_connentions</h3><p>用于设置每个worker_process最大的连接数。语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">worker_process</span> number</span><br></pre></td></tr></table></figure><p></p><p>该指令只能在events模块中设置。</p><h3 id="指定MIME"><a href="#指定MIME" class="headerlink" title="指定MIME"></a>指定MIME</h3><p>在配置文件中，可以看到如下两条配置：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">include</span>    conf/mime.types;</span><br><span class="line"><span class="attribute">default_type</span> application/octet-stream;</span><br></pre></td></tr></table></figure><p></p><p>include指令引入了mime.types文件，其中mime.types内容如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">types</span> &#123;</span><br><span class="line">    text/html                             html htm shtml;</span><br><span class="line">    text/css                              css;</span><br><span class="line">    text/xml                              xml;</span><br><span class="line">    image/gif                             gif;</span><br><span class="line">    image/jpeg                            jpeg jpg;</span><br><span class="line">    application/javascript                js;</span><br><span class="line">    application/atom+xml                  atom;</span><br><span class="line">    application/rss+xml                   rss;</span><br><span class="line"></span><br><span class="line">    text/mathml                           mml;</span><br><span class="line">    text/plain                            txt;</span><br><span class="line">    text/vnd.sun.j2me.app-descriptor      jad;</span><br><span class="line">    text/vnd.wap.wml                      wml;</span><br><span class="line">    text/x-component                      htc;</span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">    video/3gpp                            3gpp 3gp;</span><br><span class="line">    video/mp2t                            ts;</span><br><span class="line">    video/mp4                             mp4;</span><br><span class="line">    video/mpeg                            mpeg mpg;</span><br><span class="line">    video/quicktime                       mov;</span><br><span class="line">    video/webm                            webm;</span><br><span class="line">    video/x-flv                           flv;</span><br><span class="line">    video/x-m4v                           m4v;</span><br><span class="line">    video/x-mng                           mng;</span><br><span class="line">    video/x-ms-asf                        asx asf;</span><br><span class="line">    video/x-ms-wmv                        wmv;</span><br><span class="line">    video/x-msvideo                       avi;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p><code>default_type application/octet-stream</code>指定了默认类型为二进制流。如果不指定的话，默认值为text/plain。</p><p>该指令可以在http，server或location模块中设置。</p><h3 id="自定义服务日志"><a href="#自定义服务日志" class="headerlink" title="自定义服务日志"></a>自定义服务日志</h3><p>error_log用于记录Nginx运行时的常规日志，而access_log（服务日志）是指Nginx服务器在响应各种前端请求的日志。包含两个指令：access_log和log_format。</p><p>access_log的语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">access_log</span> ptah[format[buffer=size]]</span><br></pre></td></tr></table></figure><p></p><p><code>path</code>用于指定该日志的存放路径，<code>format</code>为可选项，代指自定义服务日志的格式字符串。<code>size</code>为可选项，用于配置临时存放日志的内存缓存区大小。</p><p>log_format的语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">log_format</span> name string ...</span><br></pre></td></tr></table></figure><p></p><p><code>name</code>用于为该格式定义一个变量名，供access_log指令使用。<code>string</code>为格式字符串，比如：<code>$remote_addr - $remote_user [$time_local] $status</code>其中<code>$remote_addr</code>等为Nginx预设的一些变量，常用的变量有：</p><table><tr><td><strong>参数</strong></td><td><strong>说明</strong></td><td><strong>示例</strong></td></tr><tr><td width="192" height="29">$remote_addr</td><td width="246">客户端地址</td><td width="289">211.28.65.253</td></tr><tr><td width="192" height="29">$remote_user</td><td width="246">客户端用户名称</td><td width="289">–</td></tr><tr><td width="192" height="29"><span lang="EN-US">$time_local</span></td><td width="246">访问时间和时区</td><td width="289">18/Jul/2012:17:00:01 +0800</td></tr><tr><td width="192" height="29">$request</td><td width="246">请求的URI和HTTP协议</td><td width="289">“GET /article-10000.html HTTP/1.1”</td></tr><tr><td width="192" height="50">$http_host</td><td width="246">请求地址，即浏览器中你输入的地址（IP或域名）</td><td width="289"><a href="http://www.it300.com" target="_blank" rel="noopener">www.it300.com</a><br>192.168.100.100</td></tr><tr><td width="192" height="29">$status</td><td width="246">HTTP请求状态</td><td width="289">200</td></tr><tr><td width="192" height="29">$upstream_status</td><td width="246">upstream状态</td><td width="289">200</td></tr><tr><td width="192" height="29">$body_bytes_sent</td><td width="246">发送给客户端文件内容大小</td><td width="289">1547</td></tr><tr><td width="192" height="29"><span lang="EN-US">$http_referer</span></td><td width="246">url跳转来源</td><td width="289"><a href="https://www.baidu.com/" target="_blank" rel="noopener">https://www.baidu.com/</a></td></tr><tr><td width="192" height="62">$http_user_agent</td><td width="246">用户终端浏览器等信息</td><td width="289">“Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; GTB7.0; .NET4.0C;</td></tr><tr><td width="192" height="29"><span lang="EN-US">$ssl_protocol</span></td><td width="246">SSL协议版本</td><td width="289">TLSv1</td></tr><tr><td width="192" height="29">$ssl_cipher</td><td width="246">交换数据中的算法</td><td width="289">RC4-SHA</td></tr><tr><td width="192" height="48">$upstream_addr</td><td width="246">后台upstream的地址，即真正提供服务的主机地址</td><td width="289">10.10.10.100:80</td></tr><tr><td width="192" height="29">$request_time</td><td width="246">整个请求的总时间</td><td width="289">0.205</td></tr><tr><td width="192" height="29">$upstream_response_time</td><td width="246">请求过程中，upstream响应时间</td><td width="289">0.002</td></tr></table><p>该指令只能在http模块中设置。</p><h3 id="sendfile-amp-sendfile-max-chunk"><a href="#sendfile-amp-sendfile-max-chunk" class="headerlink" title="sendfile &amp; sendfile_max_chunk"></a>sendfile &amp; sendfile_max_chunk</h3><p>sendfile用于开启或关闭使用sendfile()传输文件。语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">sendfile</span> <span class="literal">on</span> | <span class="literal">off</span></span><br></pre></td></tr></table></figure><p></p><p>可以在http，server或location中进行配置。</p><p>sendfile_max_chunk用于设置Nginx进程中的每个worker_process每次调用sendfile()传输的数据量的最大值。默认值为0，表示没有限制。比如：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">sendfile_max_chunk</span> <span class="number">128k</span></span><br></pre></td></tr></table></figure><p></p><p>该指令可以在http，server或location块中配置。</p><h3 id="keepalive-timeout"><a href="#keepalive-timeout" class="headerlink" title="keepalive_timeout"></a>keepalive_timeout</h3><p>用于设置Nginx服务器与用户建立会话连接保持的时间，语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">keepalive_timeout</span> timeout[header_timeout]</span><br></pre></td></tr></table></figure><p></p><p><code>timeout</code>用于设置服务器端保持连接的时间；<code>header_timeout</code>为可选项，用于配置应答报文头部的Keep-Alive域的值。</p><p>该指令可以在http，server和location块中配置。</p><h3 id="keepalive-requests"><a href="#keepalive-requests" class="headerlink" title="keepalive_requests"></a>keepalive_requests</h3><p>用于限制用户通过某一连接向服务器发送请求的次数，语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">keepalive_requests</span> number</span><br></pre></td></tr></table></figure><p></p><p>默认值为100，可以在http，server和location块中配置。</p><h3 id="listen"><a href="#listen" class="headerlink" title="listen"></a>listen</h3><p>该指令用于配置监听。配置方法主要有三种：</p><p>1、配置监听的IP地址：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">listen</span> address[:port] [default_server] [setfib=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [deferred] [accept_filter=filter] [bind] [ssl]</span><br></pre></td></tr></table></figure><p></p><p>2、配置监听端口</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">listen</span> port [default_server] [setfib=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [deferred] [accept_filter=filter] [bind] [ipv6only=<span class="literal">on</span>|<span class="literal">off</span>] [ssl]</span><br></pre></td></tr></table></figure><p></p><p>3、配置UNIX Domain Socket</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">listen</span> unix:path [default_server] [setfib=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [deferred] [accept_filter=filter] [bind] [ssl]</span><br></pre></td></tr></table></figure><p></p><ul><li><p><code>address</code>，IP地址，如果是IPv6的地址，需使用[]，比如[fe80 ::1]。</p></li><li><p><code>port</code>，端口号。</p></li><li><p><code>path</code>，socket文件路径，如/var/run/nginx.sock等。</p></li><li><p><code>default_server</code>，标识符，表示设置为默认主机。</p></li><li><p><code>rcvbuf=size</code>，设置监听socket接收缓存区大小。</p></li><li><p><code>sndbuf=size</code>，设置监听socket发送缓存区大小。</p></li><li><p><code>deferred</code>，标识符，将accept()设置为Deferred模式。</p></li><li><p><code>accept_filter=filter</code>，设置监听端口对请求的过滤 ，被过滤的内容不能被接收和处理。</p></li><li><p><code>ssl</code>，标识符，设置会话连接使用SSL模式进行。</p></li></ul><p>一些例子：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">listen</span> *:<span class="number">80</span> | *:<span class="number">8080</span>;  <span class="comment">#监听所有80端口和8080端口</span></span><br><span class="line"><span class="attribute">listen</span> <span class="number">192.168.1.10:8080</span>; 　<span class="comment">#监听具体IP和具体端口上的连接</span></span><br><span class="line"><span class="attribute">listen</span> <span class="number">8000</span>;  <span class="comment">#监听所有IP地址的8000端口，等同于 listen *:8000</span></span><br><span class="line"><span class="attribute">listen</span> <span class="number">192.168.1.10</span> default_server;  <span class="comment">#设置192.168.1.10的连接请求默认由此虚拟主机处理</span></span><br></pre></td></tr></table></figure><p></p><h3 id="server-name"><a href="#server-name" class="headerlink" title="server_name"></a>server_name</h3><p>Nginx配置文件中的每个server块对于一个虚拟主机配置，server_name用于指定虚拟主机的名称，用户可通过这个名称来向此虚拟主机发送请求。server_name的配置分为名称和IP两种方式。</p><p><strong>基于名称的虚拟主机配置</strong></p><p>基于名称的虚拟主机配置时，server_name的语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">server_name</span> name ...</span><br></pre></td></tr></table></figure><p></p><p>name可以有一个或多个名称并列，用空格隔开。每个名称对应一个域名，由两段或者三段组成，之间由<code>.</code>隔开。比如：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">server_name</span> www.mrbird.cc mrbird.cc;</span><br></pre></td></tr></table></figure><p></p><p>1、在name中可以使用通配符<code>*</code>，通配符可用在三段式域名的头或尾，或两段式域名的尾部，比如：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">server_name</span> <span class="regexp">*.mrbird.cc</span> <span class="regexp">mrbird.*</span>;</span><br></pre></td></tr></table></figure><p></p><p>2、在name中还可以使用正则表达式。使用<code>~</code>作为正则表达式开始的标记，比如：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">server_name</span> ~^www\d+\.mrbird\.cc$;</span><br></pre></td></tr></table></figure><p></p><p>此时比如通过<code>www1.mrbird.cc</code>可以访问Nginx服务，而<code>www.mrbird.cc</code>不可以。</p><p>name中的正则表达式支持字符串捕获功能，字符串捕获通过<code>( )</code>来拾取后面不紧跟其他的正则表达式的字符。一个正则表达式中可以存在多个不嵌套的小括号，这些内容会从左到右依次存放在变量<code>$1</code>、<code>$2</code>、<code>$3</code>……中。下文使用时就可直接使用这些变量，作用域为当前的server块。</p><p>比如有如下的server_name配置：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">server_name</span> ~^www\.(.+)\.cc$;</span><br></pre></td></tr></table></figure><p></p><p>当通过<code>www.mrbird.cc</code>访问Nginx服务器时，将会被上面的正则表达式匹配成功，mrbird将会被捕获，并且赋值给$1。</p><p>由于有两种匹配的方式，所以有可能出现两种情况都匹配的时候，这时候Nginx按照以下的优先级进行选择：</p><ol><li><p>准确匹配server_name。</p></li><li><p>通配符在开始时匹配server_name成功。</p></li><li><p>通配符在结束时匹配server_name成功。</p></li><li><p>正则表达式匹配server_name成功。</p></li></ol><p>此外，如果server_name被处于同一优先级的匹配方式多次匹配成功，则以首先匹配成功的为主。</p><p><strong>基于IP的虚拟主机配置</strong></p><p>Linux操作系统支持IP别名的添加，配置基于IP的虚拟主机，即为Nginx服务器提供的每台虚拟主机配置一个不同的IP。</p><p>查看当前网络配置：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># ifconfig</span></span><br><span class="line"><span class="attribute">ens33</span>     Link encap:Ethernet  HWaddr <span class="number">00</span>:0c:<span class="number">29</span>:<span class="number">25</span>:f3:bb  </span><br><span class="line">          inet addr:<span class="number">192.168.112.128</span>  Bcast:<span class="number">192.168.112.255</span>  Mask:<span class="number">255.255.255.0</span></span><br><span class="line">          inet6 addr: fe80::4fe4:f0e0:9e9b:7ec/<span class="number">64</span> Scope:Link</span><br><span class="line">          UP BROADCAST RUNNING MULTICAST  MTU:<span class="number">1500</span>  Metric:<span class="number">1</span></span><br><span class="line">          RX packets:<span class="number">360100</span> errors:<span class="number">0</span> dropped:<span class="number">0</span> overruns:<span class="number">0</span> frame:<span class="number">0</span></span><br><span class="line">          TX packets:<span class="number">89081</span> errors:<span class="number">0</span> dropped:<span class="number">0</span> overruns:<span class="number">0</span> carrier:<span class="number">0</span></span><br><span class="line">          collisions:<span class="number">0</span> txqueuelen:<span class="number">1000</span> </span><br><span class="line">          RX bytes:<span class="number">504446360</span> (<span class="number">504</span>.<span class="number">4</span> MB)  TX bytes:<span class="number">7347923</span> (<span class="number">7</span>.<span class="number">3</span> MB)</span><br><span class="line"></span><br><span class="line">lo        Link encap:Local Loopback  </span><br><span class="line">          inet addr:<span class="number">127.0.0.1</span>  Mask:<span class="number">255.0.0.0</span></span><br><span class="line">          inet6 addr: ::<span class="number">1</span>/<span class="number">128</span> Scope:Host</span><br><span class="line">          UP LOOPBACK RUNNING  MTU:<span class="number">65536</span>  Metric:<span class="number">1</span></span><br><span class="line">          RX packets:<span class="number">35127</span> errors:<span class="number">0</span> dropped:<span class="number">0</span> overruns:<span class="number">0</span> frame:<span class="number">0</span></span><br><span class="line">          TX packets:<span class="number">35127</span> errors:<span class="number">0</span> dropped:<span class="number">0</span> overruns:<span class="number">0</span> carrier:<span class="number">0</span></span><br><span class="line">          collisions:<span class="number">0</span> txqueuelen:<span class="number">1</span> </span><br><span class="line">          RX bytes:<span class="number">2931450</span> (<span class="number">2</span>.<span class="number">9</span> MB)  TX by</span><br></pre></td></tr></table></figure><p></p><p>ens33为正在使用的网卡，IP为<code>192.168.112.128</code>，给其添加两个IP别名<code>192.168.112.130</code>和<code>192.168.112.131</code>：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># ifconfig ens33:0 192.168.112.130 Mask 255.255.255.0 up </span></span><br><span class="line"><span class="comment"># ifconfig ens33:1 192.168.112.131 Mask 255.255.255.0 up </span></span><br><span class="line"><span class="comment"># ifconfig</span></span><br><span class="line"><span class="attribute">ens33</span>     Link encap:Ethernet  HWaddr <span class="number">00</span>:0c:<span class="number">29</span>:<span class="number">25</span>:f3:bb  </span><br><span class="line">          inet addr:<span class="number">192.168.112.128</span>  Bcast:<span class="number">192.168.112.255</span>  Mask:<span class="number">255.255.255.0</span></span><br><span class="line">          inet6 addr: fe80::4fe4:f0e0:9e9b:7ec/<span class="number">64</span> Scope:Link</span><br><span class="line">          UP BROADCAST RUNNING MULTICAST  MTU:<span class="number">1500</span>  Metric:<span class="number">1</span></span><br><span class="line">          RX packets:<span class="number">360100</span> errors:<span class="number">0</span> dropped:<span class="number">0</span> overruns:<span class="number">0</span> frame:<span class="number">0</span></span><br><span class="line">          TX packets:<span class="number">89081</span> errors:<span class="number">0</span> dropped:<span class="number">0</span> overruns:<span class="number">0</span> carrier:<span class="number">0</span></span><br><span class="line">          collisions:<span class="number">0</span> txqueuelen:<span class="number">1000</span> </span><br><span class="line">          RX bytes:<span class="number">504446360</span> (<span class="number">504</span>.<span class="number">4</span> MB)  TX bytes:<span class="number">7347923</span> (<span class="number">7</span>.<span class="number">3</span> MB)</span><br><span class="line"></span><br><span class="line">ens33:<span class="number">0</span>   Link encap:Ethernet  HWaddr <span class="number">00</span>:0c:<span class="number">29</span>:<span class="number">25</span>:f3:bb  </span><br><span class="line">          inet addr:<span class="number">192.168.112.130</span>  Bcast:<span class="number">192.168.112.255</span>  Mask:<span class="number">255.255.255.0</span></span><br><span class="line">          UP BROADCAST RUNNING MULTICAST  MTU:<span class="number">1500</span>  Metric:<span class="number">1</span></span><br><span class="line"></span><br><span class="line">ens33:<span class="number">1</span>   Link encap:Ethernet  HWaddr <span class="number">00</span>:0c:<span class="number">29</span>:<span class="number">25</span>:f3:bb  </span><br><span class="line">          inet addr:<span class="number">192.168.112.131</span>  Bcast:<span class="number">192.168.112.255</span>  Mask:<span class="number">255.255.255.0</span></span><br><span class="line">          UP BROADCAST RUNNING MULTICAST  MTU:<span class="number">1500</span>  Metric:<span class="number">1</span></span><br><span class="line"></span><br><span class="line">lo        Link encap:Local Loopback  </span><br><span class="line">          inet addr:<span class="number">127.0.0.1</span>  Mask:<span class="number">255.0.0.0</span></span><br><span class="line">          inet6 addr: ::<span class="number">1</span>/<span class="number">128</span> Scope:Host</span><br><span class="line">          UP LOOPBACK RUNNING  MTU:<span class="number">65536</span>  Metric:<span class="number">1</span></span><br><span class="line">          RX packets:<span class="number">221</span> errors:<span class="number">0</span> dropped:<span class="number">0</span> overruns:<span class="number">0</span> frame:<span class="number">0</span></span><br><span class="line">          TX packets:<span class="number">221</span> errors:<span class="number">0</span> dropped:<span class="number">0</span> overruns:<span class="number">0</span> carrier:<span class="number">0</span></span><br><span class="line">          collisions:<span class="number">0</span> txqueuelen:<span class="number">1</span> </span><br><span class="line">          RX bytes:<span class="number">16787</span> (<span class="number">16</span>.<span class="number">7</span> KB)  TX bytes:<span class="number">16787</span> (<span class="number">16</span>.<span class="number">7</span> KB)</span><br></pre></td></tr></table></figure><p></p><p>关于给网卡添加多个IP别名可以参考<a href="http://www.cnblogs.com/biaopei/p/7730517.html" target="_blank" rel="noopener">http://www.cnblogs.com/biaopei/p/7730517.html</a></p><p>这时候就可以在Nginx配置文件中配置两台基于IP配置的虚拟主机了：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">  <span class="section">http</span> &#123;</span><br><span class="line">  	...</span><br><span class="line">  	<span class="section">server</span> &#123;</span><br><span class="line">  		listen: 80;</span><br><span class="line">  		server_name: 192.168.112.130;</span><br><span class="line">  		...</span><br><span class="line">  	&#125;</span><br><span class="line">  	<span class="section">server</span> &#123;</span><br><span class="line">  		listen: 80;</span><br><span class="line">  		server_name: 192.168.112.131;</span><br><span class="line">  	&#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure><p></p><h3 id="location块"><a href="#location块" class="headerlink" title="location块"></a>location块</h3><p>location语法如下：</p><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">location [ = | ~ | ~* | ^~ ] uri &#123; ... &#125;</span><br></pre></td></tr></table></figure><p></p><p>uri是待匹配的请求字符串，可以是标准uri（不含正则表达式）和正则uri。</p><ul><li><p><code>=</code>用于标准uri前，要求请求字符串与uri严格匹配，如果成功，则停止搜索并立即处理此请求。</p></li><li><p><code>~</code>用于表示uri含正则表达式，区分大小写。</p></li><li><p><code>~*</code>用于表示uri包含正则表达式，不区分大小写。</p></li><li><p><code>^~</code>用于标准uri前，要求Nginx服务器找到和请求字符串匹配度最高的标准uri对应的location后，立即用此location处理请求，而不再使用location块中的正则uri和请求字符串做匹配。</p></li></ul><p>一个示例：</p><figure class="highlight crmsh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">location</span>  <span class="title">= / &#123;</span></span><br><span class="line"><span class="title">  # 精确匹配 / ，主机名后面不能带任何字符串</span></span><br><span class="line"><span class="title">  [ configuration</span> A ]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">location</span>  <span class="title">/ &#123;</span></span><br><span class="line"><span class="title">  # 因为所有的地址都以 / 开头，所以这条规则将匹配到所有请求</span></span><br><span class="line"><span class="title">  # 但是正则和最长字符串会优先匹配</span></span><br><span class="line"><span class="title">  [ configuration</span> B ]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">location</span> <span class="title">/documents</span>/ &#123;</span><br><span class="line">  <span class="comment"># 匹配任何以 /documents/ 开头的地址，匹配符合以后，还要继续往下搜索</span></span><br><span class="line">  <span class="comment"># 只有后面的正则表达式没有匹配到时，这一条才会采用这一条</span></span><br><span class="line">  [ configuration C ]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">location</span> <span class="title">~ /documents</span>/Abc &#123;</span><br><span class="line">  <span class="comment"># 匹配任何以 /documents/Abc 开头的地址，匹配符合以后，还要继续往下搜索</span></span><br><span class="line">  <span class="comment"># 只有后面的正则表达式没有匹配到时，这一条才会采用这一条</span></span><br><span class="line">  [ configuration CC ]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">location</span> <span class="title">^~ /images</span>/ &#123;</span><br><span class="line">  <span class="comment"># 匹配任何以 /images/ 开头的地址，匹配符合以后，停止往下搜索正则，采用这一条。</span></span><br><span class="line">  [ configuration D ]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">location</span> <span class="title">~* \.(gif</span>|jpg|jpeg)$ &#123;</span><br><span class="line">  <span class="comment"># 匹配所有以 gif,jpg或jpeg 结尾的请求</span></span><br><span class="line">  <span class="comment"># 然而，所有请求 /images/ 下的图片会被 config D 处理，因为 ^~ 到达不了这一条正则</span></span><br><span class="line">  [ configuration E ]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">location</span> <span class="title">/images</span>/ &#123;</span><br><span class="line">  <span class="comment"># 字符匹配到 /images/，继续往下，会发现 ^~ 存在</span></span><br><span class="line">  [ configuration F ]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">location</span> <span class="title">/images</span>/abc &#123;</span><br><span class="line">  <span class="comment"># 最长字符匹配到 /images/abc，继续往下，会发现 ^~ 存在</span></span><br><span class="line">  <span class="comment"># F与G的放置顺序是没有关系的</span></span><br><span class="line">  [ configuration G ]</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">location</span> <span class="title">~ /images</span>/abc/ &#123;</span><br><span class="line">  <span class="comment"># 只有去掉 config D 才有效：先最长匹配 config G 开头的地址，继续往下搜索，匹配到这一条正则，采用</span></span><br><span class="line">    [ configuration H ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>匹配的优先级：</p><p>(location =) &gt; (location 完整路径) &gt; (location ^~ 路径) &gt; (location ~,~* 正则顺序) &gt; (location 部分起始路径) &gt; (/)</p><p>按照上面的location写法，以下的匹配示例成立：</p><ul><li><p>/ -&gt; config A 精确完全匹配，即使/index.html也匹配不了。</p></li><li><p>/downloads/download.html -&gt; config B 匹配B以后，往下没有任何匹配，采用B。</p></li><li><p>/images/1.gif -&gt; configuration D 匹配到F，往下匹配到D，停止往下。</p></li><li><p>/images/abc/def -&gt; config D 最长匹配到G，往下匹配D，停止往下。 你可以看到 任何以/images/开头的都会匹配到D并停止，FG写在这里是没有任何意义的，H是永远轮不到的，这里只是为了说明匹配顺序</p></li><li><p>/documents/document.html -&gt; config C 匹配到C，往下没有任何匹配，采用C。</p></li><li><p>/documents/1.jpg -&gt; configuration E 匹配到C，往下正则匹配到E。</p></li><li><p>/documents/Abc.jpg -&gt; config CC 最长匹配到C，往下正则顺序匹配到CC，不会往下到E。</p></li></ul><blockquote><p>参考自： <a href="http://seanlook.com/2015/05/17/nginx-location-rewrite/" target="_blank" rel="noopener">seanlook’s blog</a></p></blockquote><h3 id="root"><a href="#root" class="headerlink" title="root"></a>root</h3><p>root用于配置根目录，比如有如下location配置：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">location</span> /data/ &#123;</span><br><span class="line">   <span class="attribute">root</span> /locationtest1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>当location块接收到<code>/data/index.html</code>的请求后，将在<code>/locationtest1/data/</code>目录下找到index.html。</p><p>该指令可在http，server或location块中配置。</p><h3 id="alias"><a href="#alias" class="headerlink" title="alias"></a>alias</h3><p>alias用于改变location接收到的URI请求路径。比如：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">location</span> <span class="regexp">~ ^/data/(.+\.html)$</span> &#123;</span><br><span class="line">   <span class="attribute">alias</span> /locationtest1/other/<span class="variable">$1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>当location块接收到<code>/data/index.html</code>的请求后，通过alias，Nginx到<code>/locationtest1/other/</code>目录下搜寻index.html。相当于请求从<code>/data/index.html</code>更改为了<code>/locationtest1/other/index.html</code>。</p><h3 id="index"><a href="#index" class="headerlink" title="index"></a>index</h3><p>index用于设置网站的默认首页。比如：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">location</span> <span class="regexp">~ ^/data/(.+)/web/</span> $ &#123;</span><br><span class="line">   <span class="attribute">index</span> index.<span class="variable">$1</span>.html index.html myindex.html</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>当请求为/data/locationtest1/web/时，Nginx依次搜寻index.locationtest1.html、index.html和myindex.html页面，先找到哪个就用哪个。</p><h3 id="error-page"><a href="#error-page" class="headerlink" title="error_page"></a>error_page</h3><p>该指令用于设置网站的错误页面。语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">error_page</span> code ... [=[response]] uri</span><br></pre></td></tr></table></figure><p></p><ul><li><p><code>code</code>，要处理的HTTP错误码。</p></li><li><p><code>response</code>，可选项，将code指定的错误码转化为新的错误代码response。</p></li><li><p><code>uri</code>，错误页面的路径或者网站地址。</p></li></ul><p>比如：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">error_page</span> <span class="number">404</span> /<span class="number">404</span>.html;</span><br></pre></td></tr></table></figure><p></p><p>Nginx使用<code>Nginx安装目录/html/404.html</code>页面响应404错误。</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">error_page</span> <span class="number">403</span> http://somewebsite.com/forbidden.html;</span><br></pre></td></tr></table></figure><p></p><p>Nginx使用<code>http://somewebsite.com/forbidden.html</code>页面响应403错误。</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">error_page</span> <span class="number">410</span> =<span class="number">301</span> /empty.gif;</span><br></pre></td></tr></table></figure><p></p><p>Nginx服务器产生410的HTTP消息时，使用<code>Nginx安装目录/html/empty.gif</code>返回给用户，HTTP的状态码为301。</p><p>加入想要改变<code>Nginx安装目录/html/</code>这个默认的路径，可以添加一个locaiton块：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">location</span> /<span class="number">404</span>.html &#123;</span><br><span class="line">   <span class="attribute">root</span> /myserver/errorpages/;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>该指令可在http，server和location块中配置。</p><h3 id="基于IP配置Nginx访问权限"><a href="#基于IP配置Nginx访问权限" class="headerlink" title="基于IP配置Nginx访问权限"></a>基于IP配置Nginx访问权限</h3><p>allow指令用于配置允许访问Nginx的客户端IP，语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">allow</span> address | CIDR | all</span><br></pre></td></tr></table></figure><p></p><ul><li><p><code>address</code>，指定允许访问的IP，不支持多个值，如需要有多个IP设置，需要重复使用allow命令。</p></li><li><p><code>CIDR</code>，允许访问的客户端的CIDR地址。</p></li><li><p><code>all</code>，代表允许所有的客户端访问。</p></li></ul><p>deny指令用于配置禁止访问Nginx的客户端IP，语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">deny</span> address | CIDR | all</span><br></pre></td></tr></table></figure><p></p><p>这两个指令可在http，server和location块中配置。</p><h3 id="配置Nginx密码"><a href="#配置Nginx密码" class="headerlink" title="配置Nginx密码"></a>配置Nginx密码</h3><p>auth_basic指令用于开启或者关闭认证功能，语法如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">auth_basic</span> string | <span class="literal">off</span></span><br></pre></td></tr></table></figure><p></p><ul><li><p><code>stirng</code>，开启认证功能，并配置了验证时的信息。</p></li><li><p><code>off</code>，关闭认证。</p></li></ul><p>auth_basic_user_file指令指定了包含用户名和密码的信息文件路径，语法结构为：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">auth_basic_user_file</span> file</span><br></pre></td></tr></table></figure><p></p><p>如，在nignx.conf里配置如下：</p><p><img src="img/mrbird_pohto_20171101114239.png" alt="mrbird_photo_20171101112512"></p><p>生产htpasswd文件：</p><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># printf "mrbird:$(openssl passwd -crypt 123456)\n" &gt;&gt;conf/htpasswd</span></span><br><span class="line"><span class="comment"># cat conf/htpasswd</span></span><br><span class="line">mrbird:vdV.OwMSzfJrQ</span><br></pre></td></tr></table></figure><p></p><p>重启Nginx后，访问<a href="http://localhost/index.html" target="_blank" rel="noopener">http://localhost/index.html</a>，页面显示如下：</p><p><img src="img/mrbird_photo_20171101112838.png" alt="mrbird_photo_20171101112838"></p><h2 id="配置实例"><a href="#配置实例" class="headerlink" title="配置实例"></a>配置实例</h2><p>将conf/nginx.conf配置成如下：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">worker_processes</span>  <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"><span class="attribute">error_log</span>  logs/error.log;</span><br><span class="line"><span class="section">events</span> &#123;</span><br><span class="line">    <span class="attribute">worker_connections</span>  <span class="number">1024</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="section">http</span> &#123;</span><br><span class="line">    <span class="attribute">include</span>       mime.types;</span><br><span class="line">    <span class="attribute">default_type</span>  application/octet-stream;</span><br><span class="line">    </span><br><span class="line">    <span class="attribute">log_format</span>  main  <span class="string">'<span class="variable">$remote_addr</span> - <span class="variable">$remote_user</span> [<span class="variable">$time_local</span>] "<span class="variable">$request</span>" '</span></span><br><span class="line">                       <span class="string">'<span class="variable">$status</span> <span class="variable">$body_bytes_sent</span> "<span class="variable">$http_referer</span>" '</span></span><br><span class="line">                       <span class="string">'"<span class="variable">$http_user_agent</span>" "<span class="variable">$http_x_forwarded_for</span>"'</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="attribute">sendfile</span>        <span class="literal">on</span>;</span><br><span class="line">    <span class="attribute">keepalive_timeout</span>  <span class="number">65</span>;</span><br><span class="line">    <span class="comment"># 配置server1</span></span><br><span class="line">    <span class="section">server</span> &#123;</span><br><span class="line">        <span class="attribute">listen</span>       <span class="number">8081</span>;</span><br><span class="line">        <span class="attribute">server_name</span>  localhost;</span><br><span class="line">        </span><br><span class="line">        <span class="attribute">charset</span> utf-<span class="number">8</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="attribute">access_log</span>  /myweb/server1/log/access.log  main;</span><br><span class="line">        </span><br><span class="line">        <span class="attribute">error_page</span>  <span class="number">404</span> /myweb/error/<span class="number">404</span>.html;</span><br><span class="line">        <span class="comment"># 配置/server1/location1/请求的location</span></span><br><span class="line">        <span class="attribute">location</span> /server1/location1 &#123;</span><br><span class="line">            <span class="attribute">root</span>   /myweb;</span><br><span class="line">            <span class="attribute">index</span>  index.html;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment"># 配置/server1/location2请求的location</span></span><br><span class="line">        <span class="attribute">location</span> /server1/location2 &#123;</span><br><span class="line">            <span class="attribute">root</span>   /myweb;</span><br><span class="line">            <span class="attribute">index</span>  index.html;</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment"># 配置server2</span></span><br><span class="line">    <span class="section">server</span> &#123;</span><br><span class="line">        <span class="attribute">listen</span>       <span class="number">8082</span>;</span><br><span class="line">        <span class="attribute">server_name</span>  <span class="number">192.168.112.130</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="attribute">charset</span> utf-<span class="number">8</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="attribute">access_log</span>  /myweb/server2/log/access.log  main;</span><br><span class="line">        </span><br><span class="line">        <span class="attribute">error_page</span>  <span class="number">404</span> /<span class="number">404</span>.html;</span><br><span class="line">        <span class="comment"># 配置/server2/location1/请求的locaiton</span></span><br><span class="line">        <span class="attribute">location</span> /server2/location1 &#123;</span><br><span class="line">            <span class="attribute">root</span>   /myweb;</span><br><span class="line">            <span class="attribute">index</span>  index.html;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment"># 配置/server2/location2/请求的location</span></span><br><span class="line">        <span class="attribute">location</span> /svr2/loc2 &#123;</span><br><span class="line">            <span class="attribute">alias</span>   /myweb/server2/location2; <span class="comment"># 对location的uri进行更改</span></span><br><span class="line">            <span class="attribute">index</span>  index.html;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment"># 重定向404页面地址</span></span><br><span class="line">        <span class="attribute">location</span> = /<span class="number">404</span>.html &#123;</span><br><span class="line">            <span class="attribute">root</span> /myweb/error;</span><br><span class="line">            <span class="attribute">index</span> <span class="number">404</span>.html;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>构建一个静态网站，目录结构如下：</p><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">/myweb/</span><br><span class="line">├── error</span><br><span class="line">│   └── 404.html</span><br><span class="line">├── server1</span><br><span class="line">│   ├── location1</span><br><span class="line">│   │   └── index.html</span><br><span class="line">│   ├── location2</span><br><span class="line">│   │   └── index.html</span><br><span class="line">│   └── log</span><br><span class="line">│       └── access.log</span><br><span class="line">└── server2</span><br><span class="line">    ├── location1</span><br><span class="line">    │   └── index.html</span><br><span class="line">    ├── location2</span><br><span class="line">    │   └── index.html</span><br><span class="line">    └── log</span><br><span class="line">        └── access.log</span><br></pre></td></tr></table></figure><p></p><p>启动Nginx服务：</p><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># /nginx/sbin/nginx -t</span></span><br><span class="line">nginx: the configuration file /nginx/conf/nginx.conf syntax is ok</span><br><span class="line">nginx: configuration file /nginx/conf/nginx.conf test is successful</span><br><span class="line"><span class="comment"># /nginx/sbin/nginx</span></span><br></pre></td></tr></table></figure><p></p><p>访问<a href="http://localhost:8081/server1/location1/" target="_blank" rel="noopener">http://localhost:8081/server1/location1/</a>：</p><p><img src="img/mrbird_photo_20171101151244.png" alt="mrbird_photo_20171101151244.png"></p><p>访问<a href="http://localhost:8081/server1/location2/" target="_blank" rel="noopener">http://localhost:8081/server1/location2/</a>：</p><p><img src="img/QQ截图20171101151332.png" alt="QQ截图20171101151332.png"></p><p>访问<a href="http://192.168.112.130:8082/server2/location1/" target="_blank" rel="noopener">http://192.168.112.130:8082/server2/location1/</a>：</p><p><img src="img/QQ截图20171101151521.png" alt="QQ截图20171101151521.png"></p><p>访问<a href="http://192.168.112.130:8082/svr2/loc2/" target="_blank" rel="noopener">http://192.168.112.130:8082/svr2/loc2/</a>：</p><p><img src="img/QQ截图20171101151607.png" alt="QQ截图20171101151607.png"></p><p>访问<a href="http://192.168.112.130:8082/svr2/loc3/" target="_blank" rel="noopener">http://192.168.112.130:8082/svr2/loc3/</a>：</p><p><img src="img/QQ截图20171101151711.png" alt="QQ截图20171101151711.png"></p><p>结果证明，上述配置正确。</p><script>$(".post-body a").not(".thispage").addClass("ignore-href").attr("target","_blank")</script></div><div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center;color:#878787"><div>请作者喝瓶肥宅水~</div><button id="rewardButton" style="margin-top:10px" disable="enable" onclick='var e=document.getElementById("QR");"none"===e.style.display?e.style.display="block":e.style.display="none"'><span style="height:46px;width:46px;line-height:46px;border-radius:50%;color:#fe5f55;font-weight:600;background:#ffd5be;border:none;box-shadow:0 4px 8px 0 rgba(255,213,190,.4)">￥</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/img/wechat_pay.png" alt="MrBird WeChat Pay"></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/img/ali_pay.png" alt="MrBird Alipay"></div></div></div><style>#QR img{width:auto;margin:.8em 1em 0 1em}</style></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong> MrBird</li><li class="post-copyright-link"><strong>本文链接：</strong> <a href="http://mrbird.cc/Nginx basic config.html" title="Nginx的基本配置">http://mrbird.cc/Nginx basic config.html</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li></ul></div><footer class="post-footer"><div class="post-tags" style="margin-bottom:1.3rem"><a href="/tags/Nginx/" rel="tag"># Nginx</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/Nginx install deploy.html" rel="next" title="Nginx安装与部署"><i class="fa fa-chevron-left"></i> Nginx安装与部署</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/Nginx-Gzip压缩.html" rel="prev" title="Nginx Gzip压缩">Nginx Gzip压缩 <i class="fa fa-chevron-right"></i></a></div></div></footer></article><hr><div id="container"></div><div class="post-spread"><div id="comment-div"></div><style>.valine .vlist{margin-bottom:3rem}.valine .vwrap .vcontrol .col.col-60{text-align:left}.valine .vlist .vcard .vhead,.valine .vlist .vcard section .vfooter{text-align:left}.valine .vlist .vcard section{padding-bottom:.5rem!important}.vname{color:#42b983!important}.valine .vinfo .col{text-align:left;margin-left:-27rem}div#comment-div{margin-bottom:-8rem}.valine .vlist .vcard .vcontent .code,.valine .vlist .vcard .vcontent code,.valine .vlist .vcard .vcontent pre{background:#fbfbfb}.valine .vlist .vcard .vcontent a{color:#42b983}.valine .vlist .vcard .vimg{border-radius:3px}.valine .vbtn{border-radius:2px;padding:.3rem 1.25rem}.valine .vbtn:active,.valine .vbtn:hover{color:#42b983;border-color:#42b983;background-color:#fff}.valine .vwrap .vheader .vinput:focus{border-bottom-color:#42b983}.valine .vlist .vcard .vcontent.expand:before{background:-webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(0,0%,100%,.2)));background:linear-gradient(180deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2))}.valine .vlist .vcard .vcontent.expand:after{content:"点击展开";font-size:.4rem;text-align:right;left:-1rem;background:hsla(0,0%,100%,.2)}.valine .vlist .vcard section .vfooter .vat{color:#b3b3b3}.valine .vlist .vcard section .vfooter .vat:hover{color:#42b983}.vcontent img{margin:0}.valine .info{display:none}</style><script type="text/javascript" src="/js/av.min.js"></script><script type="text/javascript" src="/js/Valine.min.js"></script><script type="text/javascript" src="/js/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE),new Valine({el:"#comment-div",notify:!1,verify:!0,appId:"SMcDFP1bN1jgb9Lo8JmtICHm-gzGzoHsz",appKey:"dH4nrUrt3V5XiJiI6Qyejnbi",placeholder:"",path:window.location.pathname,avatar:"monsterid",guest_info:["nick","mail","link"]});var chicken='<a href="#"><img src="https://image.uisdc.com/wp-content/uploads/2018/06/uisdc-chat-chicken.gif" class="checken"></a>';$("#comment-div").prepend(chicken)</script></div></div><script>var $bqinline=$("img[alt='bq-inline']");$bqinline.css({width:"2.3rem",height:"2.3rem",display:"inline","vertical-align":"text-bottom"})</script></div><div class="comments" id="comments"></div></div><aside id="sidebar" class="sidebar" onselectstart="return!1"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">Contents</li><li class="sidebar-nav-overview" data-target="site-overview">Site Preview</li></ul><section class="site-overview sidebar-panel"><div class="sidebar-sticky sticky"><div itemscope itemtype="http://schema.org/Person"><div class="author__avatar"><img src="/images/blogImage.jpg" class="author__avatar" alt="MrBird" itemprop="image"></div><div class="author__content"><h3 class="author__name" itemprop="name">MrBird's Blog</h3><p class="author__bio" itemprop="description">A simple blog, code repository, just keep blogging</p></div><div class="author__urls-wrapper"><button class="btn btn--inverse">Follow</button><ul class="author__urls social-icons"><li><a href="http://map.baidu.com/?newmap=1&s=s%26wd%3D%E7%A6%8F%E5%B7%9E%E5%B8%82%26c%3D300&from=alamap&tpl=mapcity" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-map-marker" aria-hidden="true"></i>&nbsp;&nbsp;FuZhou,CN</a></li><li><a href="https://love.mrbird.cc" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-diamond" aria-hidden="true"></i>&nbsp;&nbsp;Love</a></li><li><a href="https://cloud.mrbird.cn" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-chain" aria-hidden="true"></i>&nbsp;&nbsp;FEBS</a></li><li><a href="/atom.xml" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-rss" aria-hidden="true"></i>&nbsp;&nbsp;RSS</a></li><li><a href="https://gitee.com/mrbirdd" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-codepen" aria-hidden="true"></i>&nbsp;&nbsp;Gitee</a></li><li><a href="https://github.com/wuyouzhuguli" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-github-alt" aria-hidden="true"></i>&nbsp;&nbsp;GitHub</a></li><li><a href="javascript:;" class="popup-trigger"><i class="fa fa-fw fa-search" aria-hidden="true"></i>&nbsp;&nbsp;Search</a></li></ul></div></div></div><script>var $urls=$(".author__urls").find("a");$urls.each(function(){var o=$(this);o.mouseenter(function(){o.css({color:"#414547"})}),o.mouseleave(function(){o.css({color:""})})})</script></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Nginx基础配置指令"><span class="nav-number">1.</span> <span class="nav-text">Nginx基础配置指令</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#user"><span class="nav-number">1.1.</span> <span class="nav-text">user</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#worker-processes"><span class="nav-number">1.2.</span> <span class="nav-text">worker_processes</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#error-log"><span class="nav-number">1.3.</span> <span class="nav-text">error_log</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#pid"><span class="nav-number">1.4.</span> <span class="nav-text">pid</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#worker-rlimit-nofile"><span class="nav-number">1.5.</span> <span class="nav-text">worker_rlimit_nofile</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#worker-connections"><span class="nav-number">1.6.</span> <span class="nav-text">worker_connections</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#include"><span class="nav-number">1.7.</span> <span class="nav-text">include</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#accept-mutex"><span class="nav-number">1.8.</span> <span class="nav-text">accept_mutex</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#multi-accept"><span class="nav-number">1.9.</span> <span class="nav-text">multi_accept</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#use"><span class="nav-number">1.10.</span> <span class="nav-text">use</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#worker-connentions"><span class="nav-number">1.11.</span> <span class="nav-text">worker_connentions</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#指定MIME"><span class="nav-number">1.12.</span> <span class="nav-text">指定MIME</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自定义服务日志"><span class="nav-number">1.13.</span> <span class="nav-text">自定义服务日志</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#sendfile-amp-sendfile-max-chunk"><span class="nav-number">1.14.</span> <span class="nav-text">sendfile &amp; sendfile_max_chunk</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#keepalive-timeout"><span class="nav-number">1.15.</span> <span class="nav-text">keepalive_timeout</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#keepalive-requests"><span class="nav-number">1.16.</span> <span class="nav-text">keepalive_requests</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#listen"><span class="nav-number">1.17.</span> <span class="nav-text">listen</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#server-name"><span class="nav-number">1.18.</span> <span class="nav-text">server_name</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#location块"><span class="nav-number">1.19.</span> <span class="nav-text">location块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#root"><span class="nav-number">1.20.</span> <span class="nav-text">root</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#alias"><span class="nav-number">1.21.</span> <span class="nav-text">alias</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#index"><span class="nav-number">1.22.</span> <span class="nav-text">index</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#error-page"><span class="nav-number">1.23.</span> <span class="nav-text">error_page</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#基于IP配置Nginx访问权限"><span class="nav-number">1.24.</span> <span class="nav-text">基于IP配置Nginx访问权限</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置Nginx密码"><span class="nav-number">1.25.</span> <span class="nav-text">配置Nginx密码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置实例"><span class="nav-number">2.</span> <span class="nav-text">配置实例</span></a></li></ol></div></div></section></div></aside></div></main><footer id="footer" class="footer" onselectstart="return!1"><div class="footer-inner"><div class="copyright">&copy; 2016 - <span itemprop="copyrightYear">2019</span>&nbsp;&nbsp; <span class="author" itemprop="copyrightHolder">MrBird</span>&nbsp;&nbsp;|<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>&nbsp;&nbsp;UV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_uv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span> &nbsp;&nbsp;PV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_pv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span></div></div></footer><div class="back-to-top"><span style="font-family:'Source Sans Pro','Helvetica Neue',Arial,sans-serif;font-size:1.2em;font-weight:600">TOP</span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script><script type="text/javascript">function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":search_path.endsWith("json")&&(isXml=!1);var path="/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach(function(n){function r(e,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===t&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(t,e){var o="",n=e.start;return e.hits.forEach(function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r}),o+=t.substring(n,e.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url),d=[],g=[];if(""!=l&&(e.forEach(function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}d=d.concat(e(t,h,!1)),g=g.concat(e(t,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(t){t.sort(function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var C=[];0!=g.length;){var $=g[g.length-1],m=$.position,x=$.word,w=m-20,y=m+80;w<0&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),C.push(r(p,w,y,g))}C.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start});var T=parseInt("1");T>=0&&(C=C.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",C.forEach(function(t){b+="<a href='"+f+'\'><p class="search-result">'+s(p,t)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id});var a='<ul class="search-result-list">';o.forEach(function(t){a+=t.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(t){t.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(t){t.stopPropagation()}),$(document).on("keyup",function(t){var e=27===t.which&&$(".search-popup").is(":visible");e&&onPopupClose()})</script></body><script>$(function(){$("a").not(".nav-link,.cloud-tie-join-count,.ignore-href,.jstree-anchor").addClass("animsition-link")});var burst1=new mojs.Burst({left:0,top:0,radius:{5:40},children:{shape:"circle",fill:["red","cyan","orange"],fillOpacity:.8,radiusX:3.5,radiusY:3.5}});document.addEventListener("click",function(a){null==a.target.href&&"footer"!=a.target.className&&"copyright"!=a.target.className&&"author__urls social-icons"!=a.target.className&&"author__avatar"!=a.target.className&&"sidebar sidebar-active"!=a.target.className&&burst1.tune({x:a.pageX,y:a.pageY}).generate().replay()})</script><script type="text/javascript" src="/js/message.js"></script></html><!-- rebuild by neat -->